<?php

namespace apiend\models;

use Yii;
use apiend\models\User;
use common\models\user\UserConnect;
use common\models\ThirdPartyAuthorization;

/**
 * qq第三方登录授权
 * ThirdPartyQQForm
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ThirdPartyQQForm extends ThirdPartyAuthorization {

    public $access_token;
    public $openid;
    public $unionid;
    public $nickname;
    public $avatar;
    public $gender;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['client', 'openid', 'access_token'], 'required'],
            [['client'], 'in', 'range' => ['qq'], 'message' => '{attribute}不在允许的授权范围内'],
            [['nickname'], 'string', 'max' => 50],
            [['gender'], 'string', 'max' => 10],
            [['unionid', 'avatar'], 'string', 'max' => 255],
        ];
    }

    /**
     * bind
     * @return User|null the saved model or null if saving fails
     */
    public function authent() {
        if (!$this->validate()) {
            $this->dumpError('授权参数校验失败');
        }
        $client = $this->client;
        $openid = $this->openid;
        $unionid = $this->unionid;

        $condition = compact('client', 'openid', 'unionid');
        $connect = UserConnect::findOrNew($condition);
        if (!$connect->save()) {
            return false;
        }
        $connect->setCacheToken($this->attributes);
        return $connect;
    }

    /**
     * Signs user up.
     * @return User|null the saved model or null if saving fails
     */
    public function connect() {
        $auth = $this->authent();
        if ($auth === false && !($auth instanceof UserConnect)) {
            $this->dumpError('QQ授权获取失败');
        }
        if ($auth->user_id && $auth->meta && $auth->meta->mobile) {
            $token = $this->token;
            if (!$token->bindUser($auth->user_id)) {
                $this->dumpError('QQ授权信息Token绑定失败');
            }
            return $auth->meta;
        }
        return [
            'connect_id' => $auth->id
        ];
    }

}
